package com.yilijk.base.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.alibaba.android.arouter.launcher.ARouter;
import com.yilijk.base.AppBase;
import com.yilijk.base.BaseApi;
import com.yilijk.base.constants.UserInfo;
import com.yilijk.base.network.config.BaseRouter;
import com.yilijk.base.network.https.HttpUtils;

import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.UUID;

/**
 * 获取设备详细信息工具
 * DevicesUtils.setHttpUtils.getEnvironmentNo() 设置当前项目的环境 默认为线上
 */

public class DevicesUtils {

    public static String DEVICES_UUID = "";

    /**
     * 获取当前版本号
     */
    public static String getVersionName() {
        PackageManager packageManager = AppBase.getApplication().getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(AppBase.getApplication().getPackageName(), 0);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return packageInfo != null ? packageInfo.versionName : "";
    }

    /**
     * 获取当前版本号
     */
    public static int getVersionCode() {
        PackageManager packageManager = AppBase.getApplication().getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(AppBase.getApplication().getPackageName(), 0);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return packageInfo != null ? packageInfo.versionCode : 0;
    }

    /**
     * 获取当前IP
     */
    public static String getIPAddress() {
        if (!OpenUtils.getInstance().isUserAgreeChecked()) {
            return "";
        }
        @SuppressLint("MissingPermission") NetworkInfo info = ((ConnectivityManager) AppBase.getApplication()
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) AppBase.getApplication().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return "";
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    /**
     * @return 非对称加密秘钥版本（此参数放到header中）
     */
    public static String getSaltVersion() {
        return "2.0.0";
    }

    /**
     * 获取当前设备ID
     */
    public static String getDeviceId() {
        return Build.MODEL;
    }

    /**
     * 获取当前设备名臣
     */
    public static String getDeviceName() {
        return Build.DEVICE;
    }

    /**
     * 获取厂商
     */
    public static String getDeviceBrand() {
        return Build.BRAND;
    }

    /**
     * 获取制造商
     */
    public static String getDeviceManuFacturer() {
        return Build.MANUFACTURER;
    }

    /**
     * 操作系统
     * Android11
     */
    public static String getSystemVersion() {
        return "Android " + Build.VERSION.RELEASE;
    }

    /**
     * 获取SDK版本
     */
    public static String getSDKVersion() {
        return Build.VERSION.SDK;
    }

    /**
     * 设备请求号 5 代表android 医生端
     */
    public static String getTerminal() {
        BaseApi baseApi = (BaseApi) ARouter.getInstance().build(BaseRouter.Base).navigation();
        return baseApi.getTerminal();
    }

    /**
     * 是否是测试环境
     */
    public static boolean isEnvironment() {
        BaseApi baseApi = (BaseApi) ARouter.getInstance().build(BaseRouter.Base).navigation();
        return baseApi.isEnvironment();
    }

    /**
     * 是否是OnLine
     */
    public static boolean isOnline() {
        BaseApi baseApi = (BaseApi) ARouter.getInstance().build(BaseRouter.Base).navigation();
        return baseApi.isOnline();
    }

    /**
     * 是否是测试环境
     */
    public static String getDeviceNo() {
        return SharedPreferencesUtils.getInstance().getUment_String("deviceToken", "deviceTokenIsNull");
    }


    /**
     * 获取uuid
     *
     * @param context
     * @return
     */
    public static String getUUID(Context context) {
        return UUID.randomUUID().toString();
//        return getUniquePsuedoID();
//        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//            // TODO: Consider calling
//            //    ActivityCompat#requestPermissions
//            // here to request the missing permissions, and then overriding
//            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//            //                                          int[] grantResults)
//            // to handle the case where the user grants the permission. See the documentation
//            // for ActivityCompat#requestPermissions for more details.
//            return "";
//        }
//        String uuid = "";
//
//        UUID deviceUUID = getDeviceUuid(context);
//        if (deviceUUID != null) {
//            uuid = deviceUUID.toString();
//        } else {
////            uuid = getDeviceKey(context);
//        }
//        if (!TextUtils.isEmpty(uuid)) {
//            uuid = uuid.toUpperCase();
//        } else {
//            uuid = getUniquePsuedoID();
//        }
//
//        return uuid;

    }

//    public static String getUniquePsuedoID() {
//        String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10) + System.currentTimeMillis();
//        String serial = null;
//        try {
//            serial = android.os.Build.class.getField("SERIAL").get(null).toString();
//            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
//        } catch (Exception e) {
//            serial = "serial";
//        }
//        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
//    }
//
//    private static UUID getDeviceUuid(Context context) {
//
//        UUID uuid = null;
//        try {
//            String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
//            if (!"9774d56d682e549c".equals(androidId)) {
//                uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
//            }
//        } catch (Throwable e) {
//            e.printStackTrace();
//        }
//
//        return uuid;
//    }


    /**
     * //获取设备请求体
     */
    public static String getDeviceInfo() {
        HashMap<String, Object> deviceInfoMap = new HashMap<>();
        deviceInfoMap.put("currentVersion", getVersionCode());
        deviceInfoMap.put("appVersion", getVersionName());
        deviceInfoMap.put("IPAddress", getIPAddress());
        deviceInfoMap.put("deviceId", getDeviceId());
        deviceInfoMap.put("deviceName", getDeviceName());
        deviceInfoMap.put("deviceBrand", getDeviceBrand());
        deviceInfoMap.put("deviceManuFacturer", getDeviceManuFacturer());
        deviceInfoMap.put("SDKVersion", getSDKVersion());
        deviceInfoMap.put("terminal", getTerminal());
        deviceInfoMap.put("isEnvironment", isEnvironment());
        deviceInfoMap.put("deviceNo", getDeviceNo());
        return CommonUtils.getModuleCommonUtils().getMaptoJson(deviceInfoMap);
    }

    public static HashMap<String, Object> addDeviceInfo(HashMap<String, Object> map) {
        map.put("currentVersion", getVersionCode());
        map.put("appVersion", getVersionName());
        map.put("IPAddress", getIPAddress());
        map.put("deviceId", getDeviceId());
        map.put("deviceName", getDeviceName());
        map.put("deviceBrand", getDeviceBrand());
        map.put("deviceManuFacturer", getDeviceManuFacturer());
        map.put("SDKVersion", getSDKVersion());
        map.put("terminal", getTerminal());
        map.put("isEnvironment", isEnvironment());
        map.put("deviceNo", getDeviceNo());
        return map;
    }

    public static void requestPremission(Activity activity, String... strings) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            activity.requestPermissions(strings, 10001);
        }
    }

    public static boolean isPermissionExsit(Activity activity, String s) {
        PackageManager pm = activity.getPackageManager();
        boolean permission = (PackageManager.PERMISSION_GRANTED ==
                pm.checkPermission("android.permission.RECORD_AUDIO", "packageName"));
        if (permission) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 获取当前用户的TOKEN
     */
    public static String getToken() {
        return SharedPreferencesUtils.getInstance().getString(UserInfo.token, "");
    }

    public static String getChannel() {
        try {
            PackageManager pm = AppBase.getApplication().getPackageManager();
            ApplicationInfo appInfo = pm.getApplicationInfo(AppBase.getApplication().getPackageName(), PackageManager.GET_META_DATA);
            String channel = appInfo.metaData.getString("ANDROID_CHANNEL");
            if (!TextUtils.isEmpty(channel)) {
                return channel;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isChannel() {
        if ("guanwang".equals(getChannel())) {
            return false;
        }
        return true;
    }


}
